#include "connection_manager.hpp"
#include <iostream>

ConnectionManager& ConnectionManager::get_instance() {
    static ConnectionManager instance;
    return instance;
}

uint32_t ConnectionManager::add_connection(std::shared_ptr<TcpSession> session) {
    std::lock_guard<std::mutex> lock(mutex_);
    uint32_t session_id = generate_session_id();
    sessions_[session_id] = session;
    std::cout << "新连接建立 - Session ID: " << session_id 
              << ", 当前连接数: " << sessions_.size() << std::endl;
    return session_id;
}

void ConnectionManager::remove_connection(uint32_t session_id) {
    std::lock_guard<std::mutex> lock(mutex_);
    if (sessions_.erase(session_id) > 0) {
        std::cout << "连接断开 - Session ID: " << session_id 
                  << ", 当前连接数: " << sessions_.size() << std::endl;
    }
}

std::shared_ptr<TcpSession> ConnectionManager::get_connection(uint32_t session_id) {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = sessions_.find(session_id);
    return (it != sessions_.end()) ? it->second : nullptr;
}

size_t ConnectionManager::get_connection_count() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return sessions_.size();
}

void ConnectionManager::broadcast_message(const std::vector<uint8_t>& data) {
    std::lock_guard<std::mutex> lock(mutex_);
    for (const auto& [session_id, session] : sessions_) {
        try {
            session->send(data);
        } catch (const std::exception& e) {
            std::cerr << "广播消息到Session " << session_id 
                      << " 失败: " << e.what() << std::endl;
        }
    }
}
uint32_t ConnectionManager::generate_session_id() {
    return next_session_id_++; // 自动递增的会话ID
} 